package com.ruihu.admin.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruihu.admin.util.RequestTokenUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if(Objects.nonNull(RequestTokenUtil.getRequestUser())){
            Long userId = RequestTokenUtil.getRequestUser().getRequestUserId();
            this.setFieldValByName("createUser", userId, metaObject);
        }
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if(Objects.nonNull(RequestTokenUtil.getRequestUser())){
            Long userId = RequestTokenUtil.getRequestUser().getRequestUserId();
            this.setFieldValByName("updateUser",userId, metaObject);
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}